using System;
using System.IO;
using Unity.VisualScripting;
using UnityEngine;

public class FileDataHandler
{
    private string dirPath;
    private string filePath;
    private bool encrypt;
    private string codeWord = "alexdev";

    public FileDataHandler(string _dirPath, string _filePath, bool _encrypt)
    {
        dirPath = _dirPath;
        filePath = _filePath;
        encrypt = _encrypt;
    }

    public GameData LoadData()
    {
        GameData data = null;
        string fullPath = Path.Combine(dirPath, filePath);

        if (File.Exists(fullPath))
        {
            try
            {
                string loadData = "";
                using (FileStream fs = new FileStream(fullPath, FileMode.Open))
                {
                    using (StreamReader sr = new StreamReader(fs))
                    {
                        loadData = sr.ReadToEnd();
                    }

                }
                if (encrypt)
                {
                    loadData = EncryptDecrypt(loadData);
                }
                data = JsonUtility.FromJson<GameData>(loadData);
            }
            catch (Exception e)
            {
                Debug.LogError("Error on trying to load data from file: " + fullPath + "\n" + e);
            }


        }

        return data;
    }

    public void SaveData(GameData _gameData)
    {
        string fullPath = Path.Combine(dirPath, filePath);
        try
        {
            string data = JsonUtility.ToJson(_gameData, true);
            if (encrypt)
            {
                data = EncryptDecrypt(data);
            }
            using (FileStream fs = new FileStream(fullPath, FileMode.Create))
            {
                using (StreamWriter sw = new StreamWriter(fs))
                {

                    sw.Write(data);
                }
            }

        }
        catch (Exception e)
        {
            Debug.LogError("Error on trying to save data to file: " + fullPath + "\n" + e);
        }

    }

    public void Delete()
    {
        string fullPath = Path.Combine(dirPath, filePath);

        if (File.Exists(fullPath))
            File.Delete(fullPath);
    }


    string EncryptDecrypt(string _data)
    {
        string modifiedData = "";

        for (int i = 0; i < _data.Length; i++)
        {
            modifiedData += (char)(_data[i] ^ codeWord[i % codeWord.Length]);
        }

        return modifiedData;
    }

}
